package no.sachmuld.methodcombination.examples.behaviourchain.equalshashcode.v1;

import no.sachmuld.methodcombination.api.BehaviourChain;

/**
 *
 */
public class Point2D {

    private BehaviourChain<PointBehaviour> chain = new BehaviourChain<>();

    private int x;
    private int y;

    public Point2D(final int x, final int y) {

        this.x = x;
        this.y = y;

        with(new PointBehaviour() {

            @Override
            public int hashCode() {
                int result = x;
                result = 31 * result + y;
                return result;
            }

            @Override
            public boolean equals(Object obj) {
                if (Point2D.this == obj) return true;
                if (obj == null || Point2D.this.getClass() != obj.getClass()) return false;

                Point2D other = (Point2D) obj;

                if (x != other.x) return false;
                if (y != other.y) return false;

                return true;

            }

        });

    }

    @Override
    public final int hashCode() {
        int hashCode = 0;
        for (PointBehaviour behaviour : chain.bottomUp()) {
            hashCode += behaviour.hashCode();
        }
        return hashCode;
    }

    @Override
    public final boolean equals(Object obj) {
        for (PointBehaviour behaviour : chain.bottomUp()) {
            if (!behaviour.equals(obj)) {
                return false;
            }
        }
        return true;
    }

    final protected Point2D with(PointBehaviour... behaviours) {
        chain.addAll(behaviours);
        return this;
    }

}
